package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {

        if (dto==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        if (dto.getEquipmentId()==null &&(StringUtils.isBlank(dto.getPhone())||StringUtils.isBlank(dto.getPassword())))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        if (StringUtils.isNoneBlank(dto.getPhone())&&StringUtils.isNoneBlank(dto.getPassword())){
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser==null)
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"该手机号未注册");
            String str = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
            if (apUser.getPassword().equals(str)) {
                Map<String,Object> map = new HashMap<>();
                String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
                map.put("token",token);
                apUser.setSalt("");
                apUser.setPassword("");
                map.put("user",apUser);
                return ResponseResult.okResult(map);
            }else
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("token",AppJwtUtil.getToken(0L));
        return ResponseResult.okResult(map);
    }
}
